// pages/step/step.js
var CryptoJS = require('crypto-js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
      stepList:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this
    wx.login({
      success: function(res) {
        var appid = 'wxce7ffee86fc49962';
        var secret = '172c5e8a0d190b36a1d8d642f07ed444';
        if (res.code) {
          wx.showLoading({
            title: '正在加载步数',
          })
          wx.request({
            //url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' +
            url:'https://39mx35735tt8.vicp.fun/sns/jscode2session?appid='+
              appid +
              '&secret=' + secret + '&js_code=' + res.code +
              '&grant_type=authorization_code',
            header: {
              'content-type': 'json'
            },
            success: function(res) {
              var session_key = res.data.session_key;
              wx.getSetting({
                success: function(res) {
                  // 未开启微信运动授权
                  if (!res.authSetting['scope.werun']) {
                    wx.authorize({
                      scope: 'scope.werun',
                      success () {
                        console.log('werun authorized.')
                        wx.getWeRunData({
                          success: function(res) {
                            var encryptedData = res.encryptedData;
                            var iv = res.iv;
                            function decryptData(encryptedData, sessionKey, iv) {
                                const sessionKeyWordArray = CryptoJS.enc.Base64.parse(sessionKey);
                                const ivWordArray = CryptoJS.enc.Base64.parse(iv);
                                const encryptedDataWordArray = CryptoJS.enc.Base64.parse(encryptedData);
                                const decrypted = CryptoJS.AES.decrypt(
                                    {
                                        ciphertext: encryptedDataWordArray
                                    },
                                    sessionKeyWordArray,
                                    {
                                        iv: ivWordArray,
                                        mode: CryptoJS.mode.CBC,
                                        padding: CryptoJS.pad.Pkcs7
                                    }
                                );
                                const decryptedData = decrypted.toString(CryptoJS.enc.Utf8);
                                return decryptedData;
                            }
                            const decryptedData = decryptData(encryptedData, session_key, iv);
                            console.log('解密后的数据:', decryptedData);
                            var data = JSON.parse(decryptedData).stepInfoList.reverse()
                            for(var i=0;i<data.length;i++){
                                var date = new Date(data[i].timestamp * 1000);
                                data[i].year = date.getFullYear()
                                data[i].month = (date.getMonth() + 1)
                                data[i].day = date.getDate();
                            }
    
                            console.log(data)
                            
                            that.setData({
                                stepList:data
                            })
                            wx.hideLoading()
                            // wx.showModal({
                            //   title: '提示',
                            //   content: '微信步数'+data.stepInfoList[30].step,
                            //   showCancel: false,
                            //   confirmText: '知道了'
                            // })
                          },
                          fail: function(res) {
                            wx.showModal({
                              title: '提示',
                              content: '开发者未开通微信运动，请关注“微信运动”公众号后重试',
                              showCancel: false,
                              confirmText: '知道了'
                            })
                          }
                        })
                      }
                    })
                  } else {
                    wx.getWeRunData({
                      success: function(res) {
                        var encryptedData = res.encryptedData;
                        var iv = res.iv;
                        function decryptData(encryptedData, sessionKey, iv) {
                            const sessionKeyWordArray = CryptoJS.enc.Base64.parse(sessionKey);
                            const ivWordArray = CryptoJS.enc.Base64.parse(iv);
                            const encryptedDataWordArray = CryptoJS.enc.Base64.parse(encryptedData);
                            const decrypted = CryptoJS.AES.decrypt(
                                {
                                    ciphertext: encryptedDataWordArray
                                },
                                sessionKeyWordArray,
                                {
                                    iv: ivWordArray,
                                    mode: CryptoJS.mode.CBC,
                                    padding: CryptoJS.pad.Pkcs7
                                }
                            );
                            const decryptedData = decrypted.toString(CryptoJS.enc.Utf8);
                            return decryptedData;
                        }
                        const decryptedData = decryptData(encryptedData, session_key, iv);
                        console.log('解密后的数据:', decryptedData);
                        var data = JSON.parse(decryptedData).stepInfoList.reverse()
                        for(var i=0;i<data.length;i++){
                            var date = new Date(data[i].timestamp * 1000);
                            data[i].year = date.getFullYear()
                            data[i].month = (date.getMonth() + 1)
                            data[i].day = date.getDate();
                        }

                        console.log(data)
                        
                        that.setData({
                            stepList:data
                        })
                        wx.hideLoading()
                      },
                      fail: function(res) {
                        wx.showModal({
                          title: '提示',
                          content: '开发者未开通微信运动，请关注“微信运动”公众号后重试',
                          showCancel: false,
                          confirmText: '知道了'
                        })
                      }
                    })
                  }
                }
              })
            }
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})